package com.itlong.cloud.config.filelistener;


import com.alibaba.fastjson.JSON;
import com.itlong.cloud.service.RedisService;
import org.apache.commons.fileupload.ProgressListener;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.util.Date;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

@Component
public class FileUploadProgressListener implements ProgressListener {
    private static final org.slf4j.Logger log = LoggerFactory.getLogger(FileUploadProgressListener.class);

    private HttpSession session;

    @Autowired
    RedisService redisService;

    private ConcurrentHashMap map = new ConcurrentHashMap();

    private Boolean updateUploadStatus = false;

    // 构造一个线程池
    ThreadPoolExecutor threadPool = new ThreadPoolExecutor(1, 6, 3,
            TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(3)
    );

    @PostConstruct
    private void init(){
        threadPool.execute(new Task());
    }

    class Task implements Runnable{
        @Override
        public void run() {
            System.out.println(Thread.currentThread().getName() + "线程被调用了。");
            while (true) {
                try {
                    Thread.sleep(1000);
                    updateUploadStatus = true;
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public void setSession(HttpSession session, String deviceUnique, String deviceType, String fileName){
        this.session=session;
        ProgressEntity status = new ProgressEntity();
        status.setDeviceUnique(deviceUnique);
        status.setDeviceType(deviceType);
        status.setFileName(fileName);
        session.setAttribute("status", status);
    }

    /* pBytesRead  到目前为止读取文件的比特数
     * pContentLength 文件总大小
     * pItems 目前正在读取第几个文件
     */
    @Override
    public void update(long pBytesRead, long pContentLength, int pItems) {
        if(null != session) {
            ProgressEntity status = (ProgressEntity) session.getAttribute("status");
            status.setPBytesRead(pBytesRead);
            status.setPContentLength(pContentLength);
            status.setPItems(pItems);
            log.info("UploadProgressListener update ProgressEntity:  "+status.toString());
            if(updateUploadStatus || pBytesRead == pContentLength){

                map.put("phase", 1);
                map.put("createTime", new Date());
                map.put("fileName", status.getFileName());
                if(null != status.getDeviceType()){
                    map.put("deviceType", status.getDeviceType());
                }
                map.put("fileSize", pContentLength);
                map.put("uploadStatus", new BigDecimal(pBytesRead).divide(new BigDecimal(pContentLength), 2, BigDecimal.ROUND_DOWN).multiply(new BigDecimal(99)).setScale( 0, BigDecimal.ROUND_DOWN).longValue());
                redisService.set(status.getDeviceUnique(), 180L, JSON.toJSONString(map));
                log.info("获取日志redis值>>>>>>>>>>>>>>>>>>>>>" + redisService.get(status.getDeviceUnique()));
                updateUploadStatus = false;
            }
        }
    }
}
